package com.yonyou.common.service.messagecenter.rabbitmq;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class EndPoint {
	@Autowired
	@Qualifier("consumerConnection")
    private Connection connection;
	@Autowired
	@Qualifier("produceConnection")
    private Connection produceConnection;
	private Channel channel;
	private Channel produceChannel;
    protected String endPointName;
	public EndPoint() throws IOException, TimeoutException{

    }
    public EndPoint(String endpointName) throws IOException, TimeoutException{
        this.endPointName = endpointName;
    }
	public Channel getProduceChannel() {
    	if(produceChannel==null)
			try {
				produceChannel=produceConnection.createChannel();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return produceChannel;
	}
	public void setProduceChannel(Channel produceChannel) {
		this.produceChannel = produceChannel;
	}
    
    public Channel getChannel() throws IOException {
    	if(channel==null)
    		channel=connection.createChannel();
		return channel;
	}
	public void setChannel(Channel channel) {
		this.channel = channel;
	}
    public Connection getConnection() {
		return connection;
	}
	public void setConnection(Connection connection) {
		this.connection = connection;
	}
	
	public Connection getProduceConnection() {
		return produceConnection;
	}
	public void setProduceConnection(Connection produceConnection) {
		this.produceConnection = produceConnection;
	}
	public String getEndPointName() {
		return endPointName;
	}
	public void setEndPointName(String endPointName) {
		this.endPointName = endPointName;
	}
	/**
     * 关闭channel和connection。并非必须，因为隐含是自动调用的。
     * @throws IOException
     */
     public void close() throws IOException, TimeoutException{
         this.channel.close();
         this.connection.close();
     }
}
